package com.hezuti.common.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.util.Assert;

/**
 * 
 * @author xiaoyu.dou
 *
 */
public class RoutingHibernateTemplate implements InitializingBean {
	private Map<Object, HibernateTemplate> hibernateTemplates;
	/**
	 * 
	 */
	public void afterPropertiesSet() throws Exception {
		if (this.getHibernateTemplates() == null) {
			throw new IllegalArgumentException("hibernateTemplates is required");
		}
	}
	/**
	 * 
	 * @param hibernateTemplates
	 */
	public void setHibernateTemplates(Map<Object, HibernateTemplate> hibernateTemplates) {
		this.hibernateTemplates = hibernateTemplates;
	}	
	/**
	 * 
	 * @return
	 */
	public Map<Object, HibernateTemplate> getHibernateTemplates() {
		return hibernateTemplates;
	}
	/**
	 * 
	 * @param key
	 * @return
	 */
	public HibernateTemplate getHibernateTemplate(Object key) {
		return hibernateTemplates.get(key);
	}
	/**
	 * 
	 */
	public RoutingHibernateTemplate() {
	}
	/**
	 * 
	 * @param routingSessionFactory
	 */
	public RoutingHibernateTemplate(RoutingSessionFactory routingSessionFactory) {
		Assert.notNull(routingSessionFactory);
		hibernateTemplates = new HashMap<Object, HibernateTemplate>(routingSessionFactory.getSessionFactories().size());

		for (Iterator<Map.Entry<Object, SessionFactory>> it = routingSessionFactory.getSessionFactories().entrySet().iterator(); it.hasNext();) {
			Map.Entry<Object, SessionFactory> entry = (Map.Entry<Object, SessionFactory>) it.next();
			hibernateTemplates.put(entry.getKey(), createHibernateTemplate((SessionFactory) entry.getValue()));
		}
	}

	private HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
		return new HibernateTemplate(sessionFactory);
	}
}
